package thread;

class MyBlockingQueue{//String
    private static String[] data = null;

    private int size = 0;//个数
    private int head = 0;//队首
    private int tail = 0;//队尾

    //构造方法
    public MyBlockingQueue(int capacity){
        data = new String[capacity];
    }

    //put
    public void put(String s) throws InterruptedException {
        synchronized (this){
            while(size>= data.length){//为什么用while而不是if,因为wait()可能是非notify()正常唤醒时，while可以重新检测条件
                //用wait 时永远用while检查条件，不会出错
                this.wait();//wait等待期间会解锁，等待结束又会自动加锁
            }
            data[tail] = s;
            size++;
            tail++;
            if(tail>=data.length){
                tail = 0;
            }
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized(this){
            while(size == 0){
                this.wait();
            }
            String ret = data[head];
            head++;
            if(head>=data.length){
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }

}
public class Demo24 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);

        Thread producer = new Thread(() -> {
            int n = 0;
            while (true) {
                try {
                    queue.put(n + "");
                    System.out.println("生产元素 " + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread consumer = new Thread(() -> {
            while (true) {
                String n = null;
                try {
                    n = queue.take();
                    System.out.println("消费元素 " + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.start();
        consumer.start();
    }
}
